//
//  BBSignUpViewController.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/11/16.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import UIKit
import SVProgressHUD
class BBSignUpViewController: UIViewController {

    @IBOutlet weak var inviCodeTF: UITextField!
    @IBOutlet weak var emailTF: UITextField!
    @IBOutlet weak var passwordTF: UITextField!
    @IBOutlet weak var validCodeTF: UITextField!
    @IBOutlet weak var getValidBT: UIButton!
    var timer:Timer?
    private var kCountdownTime:Int = 60
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        emailTF.resignFirstResponder()
        passwordTF.resignFirstResponder()
        validCodeTF.resignFirstResponder()
        inviCodeTF.resignFirstResponder()
    }
    
    private func statCountDown(){
        getValidBT.isUserInteractionEnabled = false
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeAction), userInfo: nil, repeats: true)
    }
    
    @objc private func timeAction(){
        
        kCountdownTime = kCountdownTime - 1;
        if kCountdownTime < 0 {
            kCountdownTime = 60
            timer?.invalidate()
            timer = nil
            getValidBT.isUserInteractionEnabled = true
            getValidBT.titleLabel?.text = "Get Valid Code"
        }else{
             getValidBT.titleLabel?.text = "\(kCountdownTime)s later"
        }
    }
    
    @IBAction func sureAction(_ sender: Any) {
        if (emailTF.text?.isEmpty)! {
            SVProgressHUD.showError(withStatus: "Mailbox cannot be empty")
            return
        }
        if (!(emailTF.text?.contains("@"))!) {
            SVProgressHUD.showError(withStatus: "Incorrect e-mail format")
            return
        }
        if (validCodeTF.text?.isEmpty)! {
            SVProgressHUD.showError(withStatus: "Valid code cannot be empty")
            return
        }
        if (passwordTF.text?.isEmpty)! {
            SVProgressHUD.showError(withStatus: "password cannot be empty")
            return
        }
        if (inviCodeTF.text?.isEmpty)! {
            SVProgressHUD.showError(withStatus: "invitation code cannot be empty")
            return
        }
        let path = "user/reigster.do"
        let params = ["account":emailTF.text,"validCode":validCodeTF.text,"password":passwordTF.text,"invitationCode":inviCodeTF.text]
        AFNetWorkManager.shareNetworkTools().post(path, parameters: params, success: { (_, JSON) in
            let dict = JSON as![String:AnyObject]
            let status = dict["status"] as?NSNumber
            if status?.intValue == 0 {
                SVProgressHUD.showSuccess(withStatus: "Successful registration.")
                self.navigationController?.popViewController(animated: true)
            }else{
                SVProgressHUD.showError(withStatus:dict["msg"] as! String)
            }
           // self.navigationController?.popViewController(animated: true)
        }) { (_, error) in
            SVProgressHUD.showError(withStatus: "Sign up failed!")
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @IBAction func getValidAction(_ sender: Any) {
        statCountDown()
        if (emailTF.text?.isEmpty)! {
             SVProgressHUD.showError(withStatus: "Mailbox cannot be empty")
             return
        }
        if (!(emailTF.text?.contains("@"))!) {
            SVProgressHUD.showError(withStatus: "Incorrect e-mail format")
            return
        }
        let path = "user/validcode.do"
        let params = ["account":emailTF.text]
        AFNetWorkManager.shareNetworkTools().post(path, parameters: params, success: { (_, JSON) in
            let dict = JSON as![String:AnyObject]
            let status = dict["status"] as?NSNumber
            if status?.intValue == 0 {
                 SVProgressHUD.showSuccess(withStatus: "The verification code has been sent to your mailbox。")
            }else{
                 SVProgressHUD.showError(withStatus: "Get valid code failed!")
            }
        }) { (_, error) in
            SVProgressHUD.showError(withStatus: "Get valid code failed!")
        }
    }
}

